<?php

namespace Frieza\Modules\Topic\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\wiki\AdmWiki;
use Doraemon\cache\Queue;
use Doraemon\cache\Topic\Category;
use Doraemon\model\TopicActivity;
use Doraemon\service\admin\TopTopic as sTopTopic;
use Doraemon\service\admin\TopicPrize as sTopicPrize;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Frieza\Modules\Topic\Extensions\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\tools\ImgUrl;
use Illuminate\Support\MessageBag;
use Doraemon\model\TopicRelation;
use Doraemon\service\Topic\TopicRemark;
use Doraemon\cache\TopicCounter;
use Doraemon\model\TopicWikiRelation;
use Doraemon\model\Topic\TopicTagsRelation;
use Doraemon\model\Photos;

class TopicController extends Controller
{
    const PAGE_SIZE = 20;
    const IS_RELATION_WIKI = 1;

    const CHANNEL_TAGS_FILE = '/home/adm_rsync_dir/question_hot_tags_for_search.json';
    const RECOMMEND_ANSWER_IN_ALL = "/home/adm_rsync_dir/recommend_location_topic_in_all.dic";
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/index']
            )
            ->body(self::listAction($request));

    }

    public function iconChange(WorkContent $content, $id = 0)
    {
        $data = TopicActivity::getById($id);
        $form = new Form($data);
        $form->radio('icon_show_type', '显示角标')
            ->options([
                TopicActivity::ICON_SHOW_TYPE_OF_NONE => '不显示',
                TopicActivity::ICON_SHOW_TYPE_OF_FOREVER => '显示角标',
                TopicActivity::ICON_SHOW_TYPE_OF_TEMPORARY => '限时显示角标',
            ])
            ->when(TopicActivity::ICON_SHOW_TYPE_OF_TEMPORARY, function (Form $form) {
                $form->datetimeRange("icon_start_time", "icon_end_time", '时间范围');
            })->when('>', TopicActivity::ICON_SHOW_TYPE_OF_NONE, function (Form $form) {
                $form->radio('icon_type', '角标类型')
                    ->options(TopicActivity::ICON_TYPE_DESC);
            });
        $form->hidden('id', 'id');
        $form->attribute('id', $id);
        $form->disableReset();
        $form->action('/admin/topic/index/seticon/');
        $form->method('POST');
        return $content->body($form);
    }

    //角标设置完成跳转js
    private function closescript()
    {
        return <<<SCRIPT
        setTimeout(function () {
              parent.window.location.reload();
        }, 1200);
SCRIPT;
    }


    public function listAction($request = [])
    {
        $params = (array)$request['AND'];
        $limitArr = $request['LIMIT'];
        $hasData = true;
        if($params['tags']){
            $tags = array_filter($params['tags']);
            $topicIds = TopicTagsRelation::getTopicIds($tags);
            $topicIds = array_unique($topicIds);
            if($topicIds){
                $params['id'] = $topicIds;
            }else{
                $hasData = false;
            }
        }
        if($hasData){
            $topic_infos = TopicActivity::getTopicLists($limitArr, $params);
        }else{
            $topic_infos = [];
        }
        //获取备注信息
        $topicIds = array_column($topic_infos, 'id');
        $relations = TopicRelation::getByTopicIds($topicIds);
        $prizeList = sTopicPrize::getAllPrize();

        foreach($relations as &$relation) {
            $relation['topic_remark'] = TopicRemark::REMARK[$relation['topic_remark_id']];
        }

        //获取计数信息
        $counters = TopicCounter::getMulti($topicIds);

        $tags = \Doraemon\model\NewTag\Tag::getColumnByTag('社区标签');
        $tagRelation = TopicTagsRelation::getInfo(['status'=>TopicTagsRelation::STATUS_NORMAL]);
        $topicTagsList = array();
        foreach($tagRelation as $key => $value){
            $topicTagsList[$value['topic_id']][] = $value['tag_id'];
        }


        foreach($topic_infos as &$topic_info) {
            $topic_info['topic_remark'] = $relations[$topic_info['id']]['topic_remark'];
            $topic_info['counters'] = $counters[$topic_info['id']];
            if($topicTagsList[$topic_info['id']]){
                foreach ($topicTagsList[$topic_info['id']] as $value) {
                    $topic_info['tags'] .= $tags[$value].',';
                }
            }


        }

        $topic_infos_all = TopicActivity::getTopicLists([], $params);
        $gridModel = new pGridDataModel($topic_infos, count($topic_infos_all), [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use($prizeList) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->expandFilter();

            $grid->tools(function ($tools) {
                $tools->append("<a href='topanswerlist' class='btn btn-sm btn-dropbox' style='float: right;margin-left:5px;'>
<i class='fa fa-address-card'>&nbsp;&nbsp;回答固定位置管理</i></a>");
                $tools->append("<a href='toplist' class='btn btn-sm btn-default' style='float: right;margin-left:5px;'>
<i class='fa fa-adjust'>&nbsp;&nbsp;话题频道推荐置顶排序管理</i></a>");
                $tools->append("<a href='index/channel_info' class='btn btn-sm btn-adn' style='float: right;margin-left:5px;'>
<i class='fa fa-delicious'>&nbsp;&nbsp;编辑话题频道信息</i></a>");
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('title', '标题')->placeholder('标题');
                });
                $filter->column(1 / 2, function ($filter) {
                    $tags = \Doraemon\model\NewTag\Tag::getColumnByTag('社区标签');
                    $filter->in('tags', '社区标签(多选)')->multipleSelect($tags);
                    $filter->equal('channel_tag', '频道类别')->placeholder('频道类别');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('is_relation_wiki', '是否关联好物分类')->radio([
                        ''   => '全部',
                        0    => '否',
                        1    => '是',
                    ]);
                });
            });

            $grid->column('id')->display(function () {
                return "<a href='/admin/photo/answer/list?topic_activity_id={$this->id}' target='_blank' >$this->id</a>";
            });
            $grid->column('title', '标题')->width(150);
            $grid->column('content', '引导语')->width(150);
            $grid->column('status', '状态')->replace(TopicActivity::STATUS)->width(50);
            $grid->column('addtime', '操作时间')->display(function () {
                return '开始时间：' . date('Y-m-d H:i:s', $this->start_time) . "<br/>添加时间：" . date('Y-m-d H:i:s', $this->addtime) . "<br/>" . '修改时间：' . date('Y-m-d H:i:s',
                        $this->edittime);
            })->width(250);
            $grid->column('admin_tag', '关联信息')->display(function() use($tags){
                return "标签：". ($this->tags ? rtrim($this->tags,',') : '')   ."<br>"."频道类别：".$this->channel_tag."<br>"."备注信息：".$this->channel_tag."<br>"."回答数：".$this->counters['answer']."<br>"."关注数：".$this->counters['follow'];
            })->width(200);
            $grid->column('has_prize', '参与有奖')->display(function () use($prizeList) {
                $status = isset($prizeList[$this->id]) ? '是' : '否';
                return "<a href='/admin/topic/{$this->id}/topicPrize' target='_blank' >$status</a>";
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->prepend('<a class="fa reload-data fa-cubes" href="/admin/topic/topictab/' . $actions->row->id . '" >话题tab管理</a><br>');
                $actions->prepend('<a class="fa fa-indent reload-data" href="/admin/topic/topicbanner/' . $actions->row->id . '" >话题banner管理</a><br>');

                if ($actions->row->status == 1) {
                    $actions->prepend('<a class="fa reload-data fa-level-down" href="/admin/topic/index/setdown/' . $actions->row->id . '" >话题下架</a><br>');
                }
                if ($actions->row->status == 10) {
                    $actions->prepend('<a class="fa reload-data fa-level-up" href="/admin/topic/index/setnormal/' . $actions->row->id . '" >话题上架</a><br>');
                } else {
                    $actions->prepend('<a class="fa fa-indent reload-data" href="/admin/topic/' . $actions->row->id . '/topTopic" >置顶管理</a><br>');
                    $id = $actions->row->id;
                    $url = "/admin/topic/$id/iconchange";
                    $actions->prepend('<a class="fa reload-data fa-hand-o-up btn-icon" href="javascript:var index = layer.open({
                                type: 2,
                                title: \'角标设置\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                                });" >角标设置</a><br/>');
                }
                //引导语配置
                $actions->prepend('<a class="fa fa-indent reload-data" href="http://manage.haohaozhu.me/Admin/Question/editContentNew/id/' . $actions->row->id . '" target="_blank" >编辑引导语</a><br>');
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //删除话题
    public function del($id)
    {
        $data = TopicActivity::getById($id);
        if ($data) {
            $data['status'] = TopicActivity::STATUS_DELETE;
            $data['edittime'] = time();

            $rs = TopicActivity::updateById($id, $data);
            if ($rs) {
                // 添加到队列，更新话题
                Queue::insertQueue('TopicActivity/delTopicActivity', [
                    'id' => $id,
                ]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //下架
    public function setDown($id)
    {
        $data = TopicActivity::getById($id);
        if ($data) {
            $data['status'] = TopicActivity::STATUS_ADM_DELETE;
            $data['edittime'] = time();

            $rs = TopicActivity::updateById($id, $data);
            if ($rs) {
                // 添加到队列，更新话题
                Queue::insertQueue('TopicActivity/delTopicActivity', [
                    'id' => $id,
                ]);
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return back()->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->with(compact('error'));
            }
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    //角标设置
    public function setIcon(Request $request)
    {
        $error = new MessageBag([
            'title' => '保存失败'
        ]);
        $id = $request->post('id');
        $iconType = $request->post('icon_type');
        $iconShowType = $request->post('icon_show_type');
        $iconStartTime = $request->post('icon_start_time');
        $iconEndTime = $request->post('icon_end_time');
        $data = TopicActivity::getById($id);
        if ($data) {
            $data['edittime'] = time();
            if ($iconShowType == TopicActivity::ICON_SHOW_TYPE_OF_NONE) {
                $iconEndTime = null;
                $iconStartTime = null;
                $iconType = '';
            } elseif (!$iconType) {
                $error = new MessageBag([
                    'title' => '请设置角标类型'
                ]);
                return back()->with(compact('error'));
            }

            $data['icon_show_type'] = $iconShowType;
            $data['icon_end_time'] = $iconEndTime;
            $data['icon_start_time'] = $iconStartTime;
            $data['icon_type'] = $iconType;

            $rs = TopicActivity::updateById($id, $data);
            if ($rs) {
                // 添加到队列，更新话题
                Queue::insertQueue('TopicActivity/addTopicActivity', [
                    'id' => $id,
                ]);
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                admin_success('保存成功');
                Admin::script($this->closescript());
                return redirect('/admin/topic/index/closeview');
            } else {
                return back()->with(compact('error'));
            }
        } else {
            return back()->with(compact('error'));
        }
    }

    //角标设置弹框页面
    public function closeView(Request $request, Content $content)
    {
        Admin::script($this->closescript());
        return $content;
    }


    //上架
    public function setNormal($id)
    {
        $data['status'] = TopicActivity::STATUS_SUCCESS;
        $data['edittime'] = time();

        $rs = TopicActivity::updateById($id, $data);
        if ($rs) {
            // 添加到队列，更新话题
            Queue::insertQueue('TopicActivity/addTopicActivity', [
                'id' => $id,
            ]);
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    //添加话题页面
    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑话题';
        } else {
            $title = '添加话题';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('话题管理')
            ->breadcrumb(
                [
                    'text' => '话题列表',
                    'url'  => '/topic/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    //添加/修改页面
    private function editAction($id = 0)
    {
        $data = [];
        if ($id > 0) {
            //获取话题信息
            $data = TopicActivity::get('*', ['id' => $id, 'status' => [TopicActivity::STATUS_NORMAL, TopicActivity::STATUS_UNTREATED]]);
            //获取额外信息
            $extra_info = TopicRelation::getByTopicId($id);
            $data['show_wiki'] = (int) $extra_info['show_wiki'] ? : 0;
            $data['top_wikis'] = (string) $extra_info['top_wikis'] ? : '';
            $data['key_words'] = (string) $extra_info['key_words'] ? : '';
            $data['topic_remark'] = $extra_info['topic_remark_id'];

            foreach(TopicRemark::REMARK_RELATION as $topicType => $topicRemarks) {
                if(in_array($extra_info['topic_remark_id'], $topicRemarks)) {
                    $data['topic_remark_type'] = $topicType;
                }
            }

            $data['color'] = '#'.$data['color'];
            if(isset($data['cron_date']) && $data['cron_date'] > time()) {
                $data['now'] = 1;
                $data['cron_date'] = date('Y-m-d', $data['cron_date']);
            }
            $tag_ids = TopicTagsRelation::getTags($id);
            $data['tags'] = array_values($tag_ids);
        }

        $channel_tags = [];
        if(file_exists(self::CHANNEL_TAGS_FILE)) {
            $channel_tags_base = json_decode(file_get_contents(self::CHANNEL_TAGS_FILE), true);
            if($channel_tags_base && is_array($channel_tags_base)) {
                foreach($channel_tags_base as $channel_tag) {
                    $channel_tags[$channel_tag] = $channel_tag;
                }
            }
        }

        $form = new Form($data);
        $form->hidden('id', '话题ID');
        $form->imgUpload('cover_pic_id', '头图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->help('建议尺寸：商业-750*520 社区-750*375');
        $form->imgUpload('share_pic_id', '分享图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->setMinImageHeight(168)->setMaxImageHeight(168)->setMinImageWight(168)->setMaxImageWight(168)->help('请上传168（宽） x 168（高）尺寸的图片');
        $form->text('title', '话题标题')->required('话题标题必填');
        $form->textarea('content', '引导语')->help('引导语请在列表中 编辑引导语 项配置')->readonly();
        $form->textarea('content_desc', '正文默认文案')->help('支持换行');
        $form->textarea('suggestion', '键盘上方正文小标题')->help('以英文逗号分隔，最多五条');
    //    $form->tags('admin_tag', '标签');
        $tags = \Doraemon\model\NewTag\Tag::getColumnByTag('社区标签');
        $form->multipleSelect('tags', '社区标签')->options($tags);
        $form->tags('admin_tag', '自定义标签');
        $form->radio('channel_tag', '频道类别')->options($channel_tags)->required('频道类别必选');
        $form->color('color', '话题背景色色值');

        $form->radio('show_user', '展示发起人')->options(['1'=>'展示','0'=>'不展示'])
            ->when('=', 1, function ($form) {
                $form->radio('user_type', '发起人类型')->options(['1'=>'真实用户','2'=>'虚拟用户'])
                    ->when('=', 1, function($form) {
                        $form->number('uid', '真实用户uid');
                    })->default(1)
                    ->when('=', 2, function($form) {
                        $form->text('nick', '虚拟用户昵称');
                        $form->text('avatar', '虚拟账号头像地址');
                    });
            })->default(0);

        if($data['status'] == TopicActivity::STATUS_UNTREATED) {
            $form->radio('now', '定时发布')->options(['1'=>'是','0'=>'否'])
                ->when('=', 1, function($form) {
                    $form->date('cron_date', '定时发布时间');
                })->default(0);
        }

        $form->radio('show_wiki', '展示相关好物')->options(['1'=>'是','0'=>'否'])
            ->when('=', 1, function($form) {
                $form->textarea('top_wikis', '预置置顶wiki')->help('请填写wiki商品id，英文逗号分隔，最多预置5个商品');
                $form->textarea('key_words', 'wiki关键词配置')->help('请填写wiki关键词，英文逗号分隔，最多设置8个关键词');
            })->default(0);



        $form->imgUpload('button_pic_id', '参与话题按钮图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])->help('未上传使用默认参与按钮');

        $form->radio('topic_remark_type', '话题备注类型')->options(TopicRemark::REMARK_TYPE)
            ->when(TopicRemark::REMARK_TYPE_SALE, function($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_SALE);
            })
            ->when(TopicRemark::REMARK_TYPE_CONTENT, function($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_CONTENT);
            })
            ->when(TopicRemark::REMARK_TYPE_TOPIC, function($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_TOPIC);
            })
            ->when(TopicRemark::REMARK_TYPE_OPERATION, function($form) {
                $form->radio('topic_remark', '话题备注')->options(TopicRemark::REMARK_OPERATION);
            });

        $form->radio('is_relation_wiki', '是否是好物相关话题')->options(['1'=>'是','0'=>'否'])
            ->when(TopicRemark::REMARK_TYPE_SALE, function($form) use ($id){
                //获取已经关联的wiki
                $wikis = TopicWikiRelation::getWikiByTopicId($id);
                $categoryId = array_column($wikis,'category_id', 'category_level');
                $topCategory = AdmWiki::admGetChildCategoryMap(0);
                $form->select('category_id', '好物分类')->options($topCategory)->load('second_category_id', self::SOURCE_CATEGORY_LIST)->default($categoryId[1]);
                $secondCategory = AdmWiki::admGetChildCategoryMap($categoryId[1]);
                $form->select('second_category_id', '好物二级分类')->options($secondCategory)->default($categoryId[2]);
            })->default(0);

        $form->radio('sort_type','默认瀑布流')->options(['1'=>'热门','2'=>'最新']);

        $form->action('/admin/topic/index/save');

        return $form;
    }

    //话题保存
    public function submitTopic(Request $request)
    {
        $request = $request->all();

        $request['admin_id'] = Admin::user()->id;
        $request['start_time'] = strtotime($request['cron_date']) ? : time();
        $request['status'] = $request['start_time'] <= time() ? 1 : 0;
        $request['admin_tag'] = implode(',', array_filter($request['admin_tag']));
        $request['color'] = str_replace('#', '', $request['color']);
        $request['is_forever'] = 1;
        $request['cron_date'] = strtotime($request['cron_date']);
        $extra['show_wiki'] = (int) $request['show_wiki'];
        $extra['topic_remark_id'] = (int) $request['topic_remark'];
        $extra['top_wikis'] = implode(',', array_slice(array_unique(explode(',', $request['top_wikis'])), 0, 5));
        $extra['key_words'] = implode(',', array_slice(array_unique(explode(',', $request['key_words'])), 0, 8));
        $wikiRelation['category_id'] = $request['category_id'];
        $wikiRelation['second_category_id'] = $request['second_category_id'];
        $tags =  $request['tags'];

        unset($request['key_words']);
        unset($request['show_wiki']);
        unset($request['top_wikis']);
        unset($request['topic_remark_type']);
        unset($request['topic_remark']);
        unset($request['_token']);
        unset($request['now']);
        unset($request['category_id']);
        unset($request['second_category_id']);
        unset($request['tags']);
        if (isset($request['id']) && $request['id']) {
            //修改
            $request['edittime'] = time();
            $result = TopicActivity::updateById($request['id'], $request);
            $tags = array_filter($tags);
            TopicTagsRelation::addTags($request['id'],$tags);
            $extra_info = TopicRelation::getByTopicId($request['id']);
            $extra['admin_id'] = Admin::user()->id;
            $extra['topic_activity_id'] = $request['id'];
            if($extra_info && is_array($extra_info)) {
                $extra['edittime'] = date('Y-m-d H:i:s', time());
                TopicRelation::editData($extra, $request['id']);
            } else {
                $extra['addtime'] = date('Y-m-d H:i:s', time());
                TopicRelation::addData($extra);
            }

            if ($request['is_relation_wiki'] == self::IS_RELATION_WIKI) {
                $res1 = TopicWikiRelation::updateByTopicId($request['id'], 1, [
                    'category_id' => $wikiRelation['category_id'],
                    'update_time' => time(),
                ]);

                $res2 = TopicWikiRelation::updateByTopicId($request['id'], 2, [
                    'category_id' => $wikiRelation['second_category_id'],
                    'update_time' => time(),
                ]);

                if (!$res1 && !$res2) {
                    $this->addTopicWikiRelation($request['id'], $wikiRelation);
                }
            }
        } else {
            //添加
            $request['addtime'] = time();
            $result = TopicActivity::add($request);
            $extra['addtime'] = date('Y-m-d H:i:s', time());
            TopicRelation::addData($extra);
            //选择关联后，创建话题与wiki的关联
            if ($request['is_relation_wiki'] == self::IS_RELATION_WIKI) {
                $rowCount = $this->addTopicWikiRelation($result, $wikiRelation);
                if ($rowCount <= 0) {
                    Log::error('关联好物失败，影响行数 => ', $rowCount);
                }
            }
        }

        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);

            return back()->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    private function addTopicWikiRelation($topicId, $wikiRelation)
    {
        return TopicWikiRelation::add([
            [
                'topic_id' => $topicId,
                'category_id' => $wikiRelation['category_id'],
                'category_level' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ],
            [
                'topic_id' => $topicId,
                'category_id' => $wikiRelation['second_category_id'],
                'category_level' => 2,
                'create_time' => time(),
                'update_time' => time(),
            ]
        ]);
    }

    //话题频道信息
    public function channelInfo(Request $request, Content $content)
    {
        $tab = new Tab();

        $tab->add("话题频道管理", $this->editChannelAction());
        return $content
            ->header('话题管理')
            ->breadcrumb(
                [
                    'text' => '话题列表',
                    'url'  => '/topic/index'
                ],
                ['text' => "话题频道管理"]
            )
            ->body($tab);
    }

    public function editChannelAction()
    {
//        $channel_tags = '';
//        if(file_exists(self::CHANNEL_TAGS_FILE)) {
//            $channel_tags = json_decode(file_get_contents(self::CHANNEL_TAGS_FILE), true);
//            if($channel_tags && is_array($channel_tags)) {
//                $channel_tags = implode(',', $channel_tags);
//            }
//        }
        $data = Category::getCategory();
        if (is_array($data)) {
            $channel_tags = implode(',', $data);
        } else {
            $channel_tags = '';
        }
        $form = new Form(['channel_tags' => $channel_tags]);
        $form->textarea('channel_tags', '频道类别')->required('频道类别不可为空')->help('英文逗号分隔');

        $form->action('/admin/topic/index/channel_info/save');

        return $form;
    }

    //保存频道列表
//    public function saveChannelInfo(Request $request)
//    {
//        $request = $request->all();
//        $channel_tags = $request['channel_tags'];
//        $channel_tags_arr = explode(',', $channel_tags);
//        $channel_tags_json = json_encode($channel_tags_arr, JSON_UNESCAPED_UNICODE);
//        if(file_exists(self::CHANNEL_TAGS_FILE)) {
//            file_put_contents(self::CHANNEL_TAGS_FILE, $channel_tags_json);
//            $success = new MessageBag([
//                'title' => '保存成功'
//            ]);
//            return back()->with(compact('success'));
//        }
//        $error = new MessageBag([
//            'title' => '保存失败'
//        ]);
//        return back()->with(compact('error'));
//
//    }

    //保存频道列表
    public function saveChannelInfo(Request $request)
    {
        $request = $request->all();
        $channel_tags = $request['channel_tags'];
        $channel_tags_arr = explode(',', $channel_tags);

        $res = Category::setCategory($channel_tags_arr);
        if ($res) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {


            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 回答固定位置页面
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function topAnswerList(Request $request, Content $content)
    {
        if(file_exists(self::RECOMMEND_ANSWER_IN_ALL)) {
            $answers = file_get_contents(self::RECOMMEND_ANSWER_IN_ALL);
            $form = new Form(['text' => $answers]);
            $form->textarea('text', '回答固定位置')->rows(20)->help('填写话题id，回答id和位置，以|分隔，一行一个');
            $form->action('/admin/topic/topanswer/save');
            return $content
                ->header('回答固定位置管理')
                ->breadcrumb(
                    [
                        'text' => '话题列表',
                        'url'  => '/topic/index'
                    ],
                    ['text' => "回答固定位置管理"]
                )
                ->body($form);
        } else {
            return $content
                ->header('回答固定位置管理')
                ->breadcrumb(
                    [
                        'text' => '话题列表',
                        'url'  => '/topic/new'
                    ],
                    ['text' => "回答固定位置管理"]
                )
                ->body([]);
        }

    }

    /**
     * 回答固定位置保存
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function topAnswerSave(Request $request)
    {
        $request = $request->all();
        $answers = $request['text'];
        $list = explode(PHP_EOL,$answers);
        if($list){
            $idList = array_map(function ($data){
                return explode('|',$data)[1];
            },$list);
            $hasDown = Photos::select('id',['id'=>$idList,'is_bottom'=> Photos::IS_BOTTOM_YES]);
            if($hasDown){
                $ids = rtrim(join(',',$hasDown),',');
                throw new InputErrorException('提交失败！内容'.$ids.'已被置底，不可添加固定位', InputErrorException::DEFAULT_CODE, 'text');
            }
        }
        if(file_exists(self::RECOMMEND_ANSWER_IN_ALL)) {
            file_put_contents(self::RECOMMEND_ANSWER_IN_ALL, $answers);
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '保存失败'
        ]);
        return back()->with(compact('error'));
    }

}
